/**
 * 菜单模块数据操作文件
 */

const { sequelize } = require('./common');
const { user_address, province, city, area } = sequelize.models;

/**
 * 添加
 * @param {*} model 
 * @returns 
 */
const add = model => sequelize.transaction(async t => {
    const { province: pcdoe, city: ccode, district: acode } = model;
    const [p, c, d] = await Promise.all([province.findOne({ where: { province_code: pcdoe } }), city.findOne({ where: { city_code: ccode } }), area.findOne({ where: { area_code: acode } })]);
    Object.assign(model, {
        province_name: p.province,
        city_name: c.city,
        district_name: d.area
    });
    if (model.default == true) {
        user_address.update({ default: false }, { where: { user_id: model.user_id }, transaction: t });
    }
    return user_address.create(model, { transaction: t });
});

/**
 * 修改
 * @param {*} model 
 * @returns 
 */
const update = model => sequelize.transaction(async t => {
    const { province: pcdoe, city: ccode, district: acode } = model;
    const [p, c, d] = await Promise.all([province.findOne({ where: { province_code: pcdoe } }), city.findOne({ where: { city_code: ccode } }), area.findOne({ where: { area_code: acode } })]);
    Object.assign(model, {
        province_name: p.province,
        city_name: c.city,
        district_name: d.area
    });
    if (model.default == true) {
        const { user_id } = await user_address.findOne({ where: { id: model.id }, attributes: ['user_id'] });
        user_address.update({ default: false }, { where: { user_id }, transaction: t });
    }
    return user_address.update(model, { where: { id: model.id }, transaction: t });
});

/**
 * 删除用户地址
 * @param {*} id 
 * @returns 
 */
const deleteAddress = id => user_address.destroy({ where: { id } });

/**
 * 根据用户id获取所有地址
 * @param {*} user_id 
 * @returns 
 */
const getAll = user_id => user_address.findAll({ where: { user_id } });

/**
 * 获取所有省市区
 * @returns 
 */
const getPCD = () => Promise.all([province.findAll(), city.findAll(), area.findAll()]);

module.exports = {
    add,
    update,
    getAll,
    getPCD,
    deleteAddress,
}